<?php
/**
 * Created by PhpStorm.
 * User: hantian
 * Date: 2017/8/29
 * Time: 上午9:26
 */

namespace App\Services;

use Illuminate\Support\Facades\Redis;
use iscms\Alisms\SendsmsPusher as Sms;


class SmsServices
{
    protected static $register_mask = "jb_register";
    protected static $findPwd_mask = "jb_findPwd";

    protected static $mask_expire = 900;

    public static function getCaptcha($mobile, $type, $expire = "")
    {
        if (empty($expire)) {
            $expire = self::$mask_expire;
        }

        $sub = self::getMask($type);

        $oldCaptcha = Redis::get($sub . 'captcha:' . $mobile);
        if (empty($oldCaptcha)) {
            $captcha = mt_rand(1000, 9999);
            Redis::set($sub . 'captcha:' . $mobile, $captcha);
            Redis::expire($sub . 'captcha:' . $mobile, $expire);

        } else {
            $captcha = $oldCaptcha;
        }
        //发送短息
        $result = self::sendSms($mobile, $captcha);
        if ($result['code'] != 0) {
            return ['code' => -1, 'msg' => '发送失败'];
        }
        return ['code' => 0, 'captcha' => $captcha];
    }

    public static function checkCaptcha($mobile, $captcha, $type = '')
    {
        $sub = self::getMask($type);

        $oldCaptcha = Redis::get($sub . 'captcha:' . $mobile);
        if (!empty($oldCaptcha) && preg_match('/\d{4}/', $captcha)) {
            return ($oldCaptcha == $captcha);
        }
        return false;
    }

    protected static function getMask($type)
    {
        switch ($type) {
            case 1:
                return self::$register_mask;
            case 2:
                return self::$findPwd_mask;
        }
    }

    public static function sendSms($phone, $detail)
    {
        $sms = app(Sms::class);
        $smsParams = [
            'code' => $detail,
            'product' => '加贝'
        ];
        $content = json_encode($smsParams);
        $data = $sms->send($phone, '加贝', $content, 'SMS_71525046');
        //判断是否发送成功
        if (property_exists($data, 'result')) {
            //发送成功返回成功
            return ['code' => 0, 'msg' => '发送成功'];
        } else {
            //发送失败返回失败
            return ['code' => -1, 'captcha' => '发送失败'];
        }
    }
}